package com.itheima.hmshopping.app.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

import com.itheima.hmshopping.app.config.UserHolder;
import com.itheima.hmshopping.dto.InfoDto;
import com.itheima.hmshopping.dubbo.api.UmsAdminRoleRelationApi;
import com.itheima.hmshopping.dubbo.api.UmsAdminServiceApi;
import com.itheima.hmshopping.dubbo.api.UmsMenuServiceApi;
import com.itheima.hmshopping.dubbo.api.UmsRoleServiceApi;
import com.itheima.hmshopping.entity.UmsAdmin;
import com.itheima.hmshopping.entity.UmsAdminRoleRelation;
import com.itheima.hmshopping.entity.UmsMenu;
import com.itheima.hmshopping.entity.UmsRole;

import com.itheima.hmshopping.util.JwtUtil;
import com.itheima.hmshopping.util.R;

import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class UmsAdminService {
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private UmsAdminServiceApi umsAdminServiceApi;
    @DubboReference
    private UmsMenuServiceApi umsMenuServiceApi;
    @DubboReference
    private UmsAdminRoleRelationApi umsAdminRoleRelationApi;
    @DubboReference
    private UmsRoleServiceApi umsRoleServiceApi;

    /**
     * 登录,获取token
     *
     * @param param
     * @return
     */
    public R<Map> login(Map<String, String> param) {
        //获取用户名
        String username = param.get("username");
        //获取密码
        String password = param.get("password");
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return R.error("请输入密码!");
        }
        //加密
        String md5DPassWord = DigestUtils.md5DigestAsHex(password.getBytes());
        UmsAdmin admin = umsAdminServiceApi.getUser(username);
        //判断用户是否存在
        if (!ObjectUtil.isNotNull(admin)) {
            return R.error("用户不存在");
        }
        //密码是否正确
        if (!StrUtil.equals(admin.getPassword(), md5DPassWord)) {
            return R.error("密码不正确");
        }
        //是否由权限
        if (admin.getStatus() != 1) {
            return R.error("账号已禁用!");
        }
        //获取token
        String token = JwtUtil.getToken(admin.getId());
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", "Bearer ");
        //更新登录时间信息
        admin.setLoginTime(new Date());
        umsAdminServiceApi.updateById(admin);
        return R.succeed(map, "操作成功!");
    }

    /**
     * 获取当前登录用户信息
     *
     * @param name
     * @return
     */
    public R<InfoDto> info(String name) {
        InfoDto infoDto = new InfoDto();
        UmsAdmin user=new UmsAdmin();
        if (StrUtil.isBlank(name)){
            Long id = UserHolder.getUserId();
            user = umsAdminServiceApi.selectid(id);
        }
        List<UmsMenu> list = umsMenuServiceApi.alls();
        UmsAdminRoleRelation umsAdminRoleRelation = umsAdminRoleRelationApi.selectId(user.getId());
        //判断账户权限
        if (umsAdminRoleRelation.getRoleId() == 5) {
            List<UmsRole> umsRole = umsRoleServiceApi.selectAll();
            List<String> roles = CollUtil.getFieldValues(umsRole, "name", String.class);
            String[] roles1=new String[roles.size()];
            for (int i = 0; i < roles.size(); i++) {
                roles1[i]=roles.get(i);
            }
            infoDto.setRoles(roles1);
        } else {
            UmsRole umsRole = umsRoleServiceApi.selectId(umsAdminRoleRelation.getRoleId());
            String[] roles=new String[1];
            roles[0]=umsRole.getName();
            infoDto.setRoles(roles);
        }
        infoDto.setIcon(user.getIcon());
        infoDto.setMenus(list);
        infoDto.setUsername(user.getUsername());

        return R.succeed(infoDto, "操作成功!");
    }

    /**
     * 登出
     * @return
     */
    public R logout() {
        return R.succeed(null,"");
    }

    /**
     * 刷新token
     * @return
     */
    public R refreshToken() {
        //获取token
        String token = JwtUtil.getToken(UserHolder.getUserId());
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", "Bearer ");
        return R.succeed(map, "操作成功!");
    }

    /**
     * 注册用户
     * @param umsAdminParam
     * @return
     */
    public R register(UmsAdmin umsAdminParam) {
        //更新设置时间
        umsAdminParam.setCreateTime(new Date());
        umsAdminParam.setLoginTime(new Date());
        //MD5加密
        String password = DigestUtils.md5DigestAsHex(umsAdminParam.getPassword().getBytes());
        umsAdminParam.setPassword(password);
        //添加用户数据
        UmsAdmin umsAdmin = umsAdminServiceApi.addAdmin(umsAdminParam);
        return R.succeed(umsAdmin,"注册成功!");
    }
}
